package com.centaline.androidsalesblog.activities.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;

import com.bumptech.glide.load.engine.cache.DiskCache;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.UserOperate;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.rx.RxFolder;
import com.centanet.framework.utils.SprfUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 设置
 * <p/>
 * Created by fusl1 on 2015/12/25.
 * Modify by Lihq on 2016/01/20
 */
public class SettingsActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout rl_settings_personal_data, rl_settings_push;
    private SwitchCompat sc_settings;
    private AppCompatTextView atv_cache;
    private AppCompatTextView atv_exit;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_settings;
    }

    @Override
    protected void findViews() {
        rl_settings_personal_data = (RelativeLayout) findViewById(R.id.rl_settings_personal_data);
        rl_settings_push = (RelativeLayout) findViewById(R.id.rl_settings_push);
        sc_settings = (SwitchCompat) findViewById(R.id.sc_settings);
        atv_cache = (AppCompatTextView) findViewById(R.id.atv_cache);
        atv_exit = (AppCompatTextView) findViewById(R.id.atv_exit);
    }

    @Override
    protected void initViews() {
        setUniversalToolbar(R.string.title_settings);
        sc_settings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SprfUtil.setBoolean(SettingsActivity.this, SprfConstant.WIFI_SWITCH, isChecked);
                GlideLoad.loadWithWifi = !isChecked;
                baiduEvent("N1_1_Click");
            }
        });
        sc_settings.setChecked(SprfUtil.getBoolean(this, SprfConstant.WIFI_SWITCH, true));

        RxView.clicks(atv_exit)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        new AlertDialog.Builder(SettingsActivity.this)
                                .setMessage("退出登录？")
                                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        logout();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create()
                                .show();
                    }
                });

        List<UserDo> login = DataSupport.findAll(UserDo.class);
        if (login != null && login.size() != 0) {
            atv_exit.setVisibility(View.VISIBLE);
        }
        RxFolder.folderSize(new File(getApplicationContext().getExternalCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        atv_cache.setText(s);
                    }
                });
        if (AppConstant.IsLogin) {
            RxDataBase.getUser()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<UserDo>() {
                        @Override
                        public void call(UserDo userDo) {
                            if (userDo != null) {
                                atv_exit.setVisibility(View.VISIBLE);
                                rl_settings_personal_data.setVisibility(View.VISIBLE);
                                rl_settings_push.setVisibility(View.VISIBLE);
                            }
                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_settings_personal_data:
                startActivity(new Intent(this, MyProfileActivity.class));
                break;
            case R.id.rl_settings_push:
                startActivity(new Intent(this, PushSettingActivity.class));
                break;
            case R.id.rl_settings_centaline:
                startActivity(new Intent(this, AboutUsActivity.class));
                baiduEvent("N1_3_Click");
                break;
            case R.id.rl_settings_cache:
                new AlertDialog.Builder(this)
                        .setMessage("清除所有的缓存？")
                        .setPositiveButton("清除", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                RxFolder.clearGlideCache(SettingsActivity.this)
                                        .compose(SettingsActivity.this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Action1<Boolean>() {
                                            @Override
                                            public void call(Boolean aBoolean) {
                                                if (aBoolean) {
                                                    snack("清除完毕");
                                                    atv_cache.setText(R.string.dialog_folder_size_null);
                                                }
                                            }
                                        });
                            }
                        }).setNegativeButton("取消", null).create().show();
                break;
            default:
                break;
        }
    }

    /**
     * 退出登录
     */
    private void logout() {
        RxDataBase.deleteUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        AppConstant.setUserLogin(SettingsActivity.this, null);
                        EventBus.getDefault().post(new UserOperate(0));
                        finish();
                    }
                });
    }
}
